#!/usr/bin/env python

from datetime import datetime, timedelta
import numpy as np
import os,re
from datetime import datetime, timedelta

siteid = 'KPNS'



def main():
    today = datetime.utcnow()
    tomorrow = today + timedelta(hours = 24)
    workdt = datetime(tomorrow.year,tomorrow.month,tomorrow.day)
    parsed = get_cmce(siteid, workdt)
    
    # Histogram the data
    plot_data(parsed)


def plot_data(parsed,workdt):
    for var in parsed.keys():

        # Get the right day's list
        varlist = [parsed[var][mem] for mem in parsed[var].keys()]

        # Plot
        import matplotlib.pyplot as plt
        plt.figure(figsize=(11,9))
        ax1 = plt.gca()
        binrge = range(int(min(varlist)), int(max(varlist))+2)
        nbinrge = [r-0.5 for r in binrge]
        n,bins,patches = ax1.hist(varlist,bins=nbinrge,align='mid',color='LightSkyBlue',label='CMCE Hist.')
        plt.ylabel('Number of Ensemble Members')
        plt.xlabel('var')
        plt.title('%s for %s on %s' % (var, siteid.upper(), workdt.strftime('%m/%d/%Y')))
        plt.show()

def get_cmce(siteid,workdt):
    #os.system('rm cmce_mos.txt')
    import itertools, re
    cmce_site = 'http://www.mdl.nws.noaa.gov/~naefs_ekdmos/text/cmce_mxmnmem_12.txt'
    # Get file from web
    os.system('wget -O cmce_mos.txt %s' % cmce_site)

    outdict = {'High Temperature' : {},
               'Low Temperature' : {},}
    # Open the file
    with open('cmce_mos.txt','r') as f:
        for key, group in itertools.groupby(f,is_separator):
            if not key:
                for item in group:
                    values = item.split()
                    if values[1] == siteid.upper():
                        # This line containes useful info
                        outtime = datetime.strptime(values[0],'%Y%m%d%H')
                        if outtime.hour == 6 and \
                           ((datetime(outtime.year,outtime.month,outtime.day)-timedelta(days=1)) == workdt): 
                           # this is the high temperature for the previous day
                           outdict['High Temperature']= {}
                           for mem in range(21):
                               try:
                                   outdict['High Temperature'][mem] = float(values[mem+2])
                               except:
                                   outdict['High Temperature'][mem] = np.nan 

                        elif outtime.hour == 18 and \
                           ((datetime(outtime.year,outtime.month,outtime.day)) == workdt): 
                           # this is the low temperature for today
                           outdict['Low Temperature'] = {}
                           for mem in range(21):
                               try:
                                   outdict['Low Temperature'][mem] = float(values[mem+2])
                               except:
                                   outdict['Low Temperature'][mem] = np.nan 
    return outdict
                       
def is_separator(line):
    testline = 'VALID TIME STN 	 MEM40 MEM41 MEM42 MEM43 MEM44 MEM45 MEM46 MEM47 MEM48 MEM49 MEM50 '
    return re.search(testline,line)

if __name__ == '__main__':
    main()

